package com.flyxiaozhu.erp.admin;


import com.flyxiaozhu.erp.core.entities.Permission;
import com.flyxiaozhu.erp.core.entities.Role;
import com.flyxiaozhu.erp.core.entities.RolePermission;
import com.flyxiaozhu.erp.core.repositories.PermissionRepository;
import com.flyxiaozhu.erp.core.repositories.RolePermissionRepository;
import com.flyxiaozhu.erp.core.repositories.RoleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
@Order(1)
public class AddPermission implements ApplicationRunner {
    @Autowired
    PermissionRepository permissionRepository;

    @Autowired
    RoleRepository roleRepository;

    @Autowired
    RolePermissionRepository rolePermissionRepository;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        Role role = roleRepository.findByName("超级管理员");
        List<RolePermission> rolePermissionList = new ArrayList<>();
        if (role == null) {
            role = new Role();
            role.setName("超级管理员");
            Long roleId = roleRepository.save(role).getId();
            System.out.println("============添加角色============");
            System.out.println(role.getName());
            List<Permission> permissionList = permissionRepository.findAll();
            for (Permission permission : permissionList) {
                RolePermission rolePermission = new RolePermission();
                rolePermission.setPermissionId(permission.getId());
                rolePermission.setRoleId(roleId);

                rolePermissionList.add(rolePermission);

                System.out.println("============添加角色权限============");
                System.out.println("角色：" + role.getName() + "，权限：" + permission.getName());
            }
            rolePermissionRepository.saveAll(rolePermissionList);
        }
    }
}
